﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml.Serialization;
namespace Ajax.Common
{
    public class SerializableHelper
    {
        /// <summary>
        /// 进行二进制序列化成一个字符串
        /// </summary>
        /// <returns>序列化代码</returns>
        public static string BinarySerialize<T>(T t)
        {
            BinaryFormatter ser = new BinaryFormatter();
            MemoryStream mStream = new MemoryStream();
            ser.Serialize(mStream, t);
            byte[] buf = mStream.ToArray();
            mStream.Close(); 
            return Encoding.UTF8.GetString(buf);
        }

        /// <summary>
        /// 字符串反序列化成一个类
        /// </summary>
        /// <param name="binary"></param>
        /// <returns></returns>
        public static T DeSerialize<T>(string strLoginUserModel)
        {
            byte[] binary = Encoding.UTF8.GetBytes(strLoginUserModel);
            BinaryFormatter ser = new BinaryFormatter();
            MemoryStream mStream = new MemoryStream(binary);
            object o = ser.Deserialize(mStream);
            mStream.Close();
            return (T)o;
        }
 
        /// <summary>
        /// 序列化泛型数组为xml文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        /// <param name="path"></param>
        public static void SerialToXml<T>(T[] items, FileInfo fi)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T[]));
            TextWriter writer = new StreamWriter(fi.FullName);
            try
            {
                xmlSerializer.Serialize(writer, items);
            }
            finally
            {
                writer.Close();
            }
        }
        /// <summary>
        /// xml 文件反序列化为泛型数组
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <returns></returns>
        public static T[] Deserial<T>(FileInfo fi)
        {
            if (fi.Exists == false) return new T[0];

            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T[]));

            FileStream fs = fi.OpenWrite();
            T[] items;
            try
            {
                items = (T[])xmlSerializer.Deserialize(fs);
            }
            finally
            {
                fs.Close();
            }
            return items;
        }

    }
}